import axios, { AxiosRequestConfig, AxiosResponse } from 'axios'
import { message } from 'ant-design-vue'
import { baseURL } from '@/api/axios-config'

const publicPath = process.env.BASE_URL || ''

message.config({
  top: '100px',
  duration: 2,
  maxCount: 1,
})

const instance = axios.create({
  baseURL,
  method: 'post',
  headers: {
    'Content-Type':
      'multipart/form-data;charset=utf-8;boundary=OCqxMF6-JxtxoMDHmoG5W5eY9MGRsTBp',
  },
})

// Add a request interceptor
instance.interceptors.request.use(
  (config: AxiosRequestConfig) => {
    // Do something before request is sent
    // console.log('request', config)
    return config
  },
  (error) => {
    // Do something with request error
    message.error('请求超时:', error.toString())
    return Promise.reject(error)
  }
)

// Add a response interceptor
instance.interceptors.response.use(
  (response: AxiosResponse) => {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    console.log('response:', response)
    switch (response.data.code) {
      case 100:
        return response
      default:
        console.log('code:', response.data.code)
        message.info(response.data.message)
        return response
    }
  },
  (error) => {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    console.log('error:')
    console.log(error.response)
    message.error(error.response.data.message)

    // 未登录
    if (error.response.data.code === 301) {
      window.location.href = `${publicPath}${
        publicPath.endsWith('/') ? '' : '/'
      }login`
    }
    return Promise.reject(error)
  }
)

export default instance
